<?php


class Wpshop_Admin
{
	private $view;
	private static $count_orders_on_page = 50;
	private static $cfromsFileForRight = "Заказ";
	public function __construct()
	{
		wp_enqueue_script("wpshop-admin", WPSHOP_URL ."/wp-shop-admin.js",array('jquery','jquery-ui-position'));
		add_action('admin_menu', array(&$this,'adminMenu'));
		
		// so... update
		if (isset($_POST['update_wpshop_settings']))
		{
			$this->updateSettingsPage();
		}
		
		$this->view = new Wpshop_View();
	}
	
	public function adminMenu()
	{
		if (function_exists('add_menu_page'))
		{
			add_menu_page( "WP Shop Settings" , "WP Shop", "activate_plugins", "wpshop_main"/*,array(&$this,"settingsAction")*/);
			add_submenu_page("wpshop_main", "WP Shop Settings", "WP Shop Settings", "activate_plugins", "wpshop_settings",array(&$this,"settingsAction"));
			add_submenu_page("wpshop_main", "WP Shop Orders", "WP Shop Orders", "activate_plugins", "wpshop_orders",array(&$this,"ordersAction"));
			add_submenu_page("wpshop_main", "WP Shop Payments", "WP Shop Payments", "activate_plugins", "wpshop_payments",array(&$this,"paymentsAction"));
			
			$delivery = new Wpshop_Delivery();
			
			add_submenu_page("wpshop_main", "WP Shop Deliveries", "WP Shop Deliveries", "activate_plugins", "wpshop_delivery",array($delivery,"deliveryAction"));
		}
	}
	
	/**
	 *
	 */
	public function ordersAction()
	{
		global $wpdb;
		$post = $_GET;
		
		if (isset($_POST['mass_action']))
		{			
			foreach($_POST['order_check'] as $order_id)
			{
				Wpshop_Orders::setStatus($order_id,$_POST['orders_status']);
				//$wpdb->query("DELETE FROM `{$wpdb->prefix}wpshop_ordered` WHERE `ordered_pid` = {$order_id}");
				//$wpdb->query("DELETE FROM `{$wpdb->prefix}wpshop_orders` WHERE `order_id` = {$order_id}");					
			}
		}
		
		
		
		// List orders
		$id = isset($_GET['order_id']) ? (int)$_GET['order_id'] : null;
		if (isset($_GET['act']) && $_GET['act'] == "edit")
		{
			if (!empty($id))
			{
				if (isset($_POST['order']['save']))
				{
					$data = array();
					$data['order_status'] = $_POST['order']['status'];
					$data['order_comment'] = $_POST['order']['comment'];
					Wpshop_Orders::getInstance()->save($id,$data);
				}
				
				$this->view->order =  $wpdb->get_row("SELECT * FROM `{$wpdb->prefix}wpshop_orders` WHERE `order_id` = '{$id}'"); 
				
				$this->view->ordered = $wpdb->get_results("SELECT * FROM `{$wpdb->prefix}wpshop_ordered` WHERE `ordered_pid` = '{$id}'");
				
				$payment = Wpshop_Payment::getInstance()->getPaymentByID($this->view->order->order_payment);
				if ($payment)
				{
					$this->view->order->payment = $payment->name;
				}
				else
				{
					$this->view->order->payment = "";
				}	
				$this->view->render("admin/orders.order.php");
				return;
			}
		}
		
		if (isset($_GET['act']) && $_GET['act'] == "delete" && !empty($id))
		{
			$wpdb->query("DELETE FROM `{$wpdb->prefix}wpshop_ordered` WHERE `ordered_pid` = {$id}");
			$wpdb->query("DELETE FROM `{$wpdb->prefix}wpshop_orders` WHERE `order_id` = {$id}");
		}
		
		$this->view->page['current'] = empty($_GET['num_page']) ? 1 : $_GET['num_page'];
		$from = ($this->view->page['current']-1) * self::$count_orders_on_page;
		
		$sqlFilter = '';
		if (isset($post['filter_payment']) && $post['filter_payment']!='')
		{
			$sqlFilter .= " AND `order_payment` = '{$post['filter_payment']}' ";
		}
		
		if (isset($post['filter_status']) && $post['filter_status']!=-1)
		{
			$sqlFilter .= " AND `order_status` = '{$post['filter_status']}' ";
		}
		// не показывать по дефолту архив
		if (!isset($post['filter_status']) || $post['filter_status'] != 5)
		{
			$sqlFilter .= " AND `order_status` <> '5' ";
		}
		
		if (isset($post['filter_delivery']) && $post['filter_delivery'] != -1 )
		{
			$sqlFilter .= " AND `order_delivery` = '{$post['filter_delivery']}' ";
		}
		
		$date = array();
		$date['min']['timestamp'] = $wpdb->get_var("SELECT MIN(`order_date`) FROM `{$wpdb->prefix}wpshop_orders`");
		$date['min']['en'] = date("Y-m-d",$date['min']['timestamp']);
		$date['min']['ru'] = date("d.m.Y",$date['min']['timestamp']);
		$date['max']['timestamp'] = $wpdb->get_var("SELECT MAX(`order_date`) FROM `{$wpdb->prefix}wpshop_orders`");
		$date['max']['en'] = date("Y-m-d",$date['max']['timestamp']);
		$date['max']['ru'] = date("d.m.Y",$date['max']['timestamp']);
		
		if (isset($post['filter_date_from']))
		{
			try
			{
				$this->view->filter_date_from = Wpshop_Utils::checkDate('ru',$post['filter_date_from']);
				$sqlFilter .= " AND `order_date` >= '" . strtotime(Wpshop_Utils::checkDate('en',$post['filter_date_from'])) . "' ";
			}
			catch(Exception $e)
			{
				$this->view->filter_date_from = $date['min']['ru'];
			}
		}
		else
		{
			$this->view->filter_date_from = $date['min']['ru'];
		}
		
		if (isset($post['filter_date_to']))
		{
			try
			{
				$this->view->filter_date_to = Wpshop_Utils::checkDate('ru',$post['filter_date_to']);
				$sqlFilter .= " AND `order_date` <= '" . strtotime(Wpshop_Utils::checkDate('en',$post['filter_date_to']). " 23:59:59") . "' ";
			}
			catch(Exception $e)
			{
				$this->view->filter_date_to = $date['max']['ru'];
			}
		}
		else
		{
			$this->view->filter_date_to = $date['max']['ru'];
		}

		$this->view->orders = $wpdb->get_results("SELECT SQL_CALC_FOUND_ROWS * FROM `{$wpdb->prefix}wpshop_orders` WHERE 1 {$sqlFilter} ORDER BY `order_date` DESC LIMIT {$from},".self::$count_orders_on_page);		
		$this->view->post = $post;	
		$this->view->page['count'] = ceil($wpdb->get_var("SELECT FOUND_ROWS();") / self::$count_orders_on_page);
		$this->view->render("admin/orders.php");
	}
	
	public function settingsAction()
	{
		$cform = get_option('wp-shop_cform');
		$css = get_option('wp-shop_cssfile');
		
		$this->view->usd_cur = get_option('wp-shop-usd');
		$this->view->eur_cur = get_option('wp-shop-eur');
		$this->view->link_ie6 = get_option('wp-shop-link_ie6');
		$this->view->payments_activate = get_option('wpshop.payments.activate');

		$this->view->opt_under_title = get_option('wpshop_price_under_title');
		$this->view->position = get_option('wp-shop_position');
		$this->view->showCost = get_option('wp-shop_show-cost');
		$this->view->f_order = self::$cfromsFileForRight;
		$this->view->discount = get_option('wpshop.cart.discount');
		$this->view->minzakaz = get_option('wpshop.cart.minzakaz');
		$this->view->minzakaz_info = get_option('wpshop.cart.minzakaz_info');
		$this->view->deliveyrCondition = get_option('wpshop.cart.deliveyrCondition');
		$this->view->email = get_option("wpshop.email");
		$this->view->noGoodText = get_option("wpshop.good.noText");
		$this->view->currency = get_option("wpshop.currency");		
		
		$cforms = Wpshop_Forms::getInstance()->getForms();
		$this->view->cforms = array();
		foreach($cforms as $i => $value)
		{
			if ($cforms[$i]['name'] == $cform)
			{
				$cforms[$i]['selected'] = 'selected="selected"';
			}
			else
			{
				$cforms[$i]['selected'] = '';	
			}
			$this->view->cforms[] = $cforms[$i];
		}
		
		$file_list = '';
		$dir = WPSHOP_DIR . "/styles/";

		if ($dh = opendir($dir))
		{
			while (($file = readdir($dh)) !== false)
			{
				if ($file != '.' AND $file != '..')
				{
					$current_file = "{$dir}{$file}";
					if (is_file($current_file))
					{
						$selected = '';
						if ($css == $file)
						{
							$selected = " selected";
						}
						$file_list .= "<option value=\"{$file}\"$selected>{$file}</option>";
					}
				}
			}
		}
		$this->view->file_list = $file_list;
		$this->view->link_to_yml = get_option('siteurl') . "/?wpshop_yml";
		
		$this->view->render("admin/settings.php");
	}
	
	
	public function updateSettingsPage()
	{
		update_option("wp-shop_cssfile",$_POST['cssfile']);
		update_option("wp-shop_cform",$_POST['cform']);
		update_option("wp-shop_position",$_POST['position']);
		update_option("wp-shop-link_ie6",$_POST['link_ie6']);
		update_option("wpshop.cart.discount",$_POST['discount']);
		update_option("wpshop.email",$_POST['wpshop_email']);
		update_option("wpshop.cart.deliveyrCondition",$_POST['deliveyrCondition']);
		update_option("wpshop.cart.minzakaz",$_POST['minzakaz']);
		update_option("wpshop.currency",$_POST['currency']);		
		update_option("wpshop.good.noText",$_POST['noGoodText']);
	
		update_option("wpshop.cart.minzakaz_info",$_POST['minzakaz_info']);	

		if (isset($_POST['wpshop_payments_activate']))
		{
			update_option("wpshop.payments.activate",1);
		}
		else
		{
			update_option("wpshop.payments.activate",0);
		}
		
		if (isset($_POST['wp-shop_show-cost']))
		{
			update_option("wp-shop_show-cost",1);
		}
		else
		{
			update_option("wp-shop_show-cost",0);
		}
	}
	
	public function paymentsAction()
	{
		if (isset($_POST['update_payments']))
		{
			$this->updatePayments();
		}
		$this->view->wm = get_option("wpshop.payments.wm");
		
		
		$this->view->cforms = Wpshop_Forms::getInstance()->getForms();
		$this->view->cash = get_option("wpshop.payments.cash");
		$this->view->robokassa = get_option("wpshop.payments.robokassa");
		$this->view->paypal = get_option("wpshop.payments.paypal");
		$this->view->vizit = get_option("wpshop.payments.vizit");
		$this->view->post = get_option("wpshop.payments.post");
		
		$this->view->deliveries = Wpshop_Delivery::getInstance()->getDeliveries();
		
		//Новая схема, сохранения данных, берем и кладем опции использую обыкновенных массивы
		$this->view->bank = get_option("wpshop.payments.bank");
		
		print_r($this->view->bank);
		echo "ssssa";
		$this->view->render("admin/payments.php");
	}
	
	public function updatePayments()
	{
		//Web money
		if (!isset($_POST['wpshop_payments_wm']['activate']))
		{
			$_POST['wpshop_payments_wm']['activate'] = 0;
		}
		update_option("wpshop.payments.wm",$_POST['wpshop_payments_wm']);
		
		//Наложный платеж
		if (!isset($_POST['wpshop_payments_cash']['activate']))
		{
			$_POST['wpshop_payments_cash']['activate'] = 0;
		}
		update_option("wpshop.payments.cash",$_POST['wpshop_payments_cash']);		
		
		
		//Банк
		if (!isset($_POST['wpshop_payments_bank']['activate']))
		{
			$_POST['wpshop_payments_bank']['activate'] = 0;
		}
		update_option("wpshop.payments.bank",$_POST['wpshop_payments_bank']);
		
		//Робокасса
		if (!isset($_POST['wpshop_payments_robokassa']['activate']))
		{
			$_POST['wpshop_payments_robokassa']['activate'] = 0;
		}
		update_option("wpshop.payments.robokassa",$_POST['wpshop_payments_robokassa']);
		
		//PayPal
		if (!isset($_POST['wpshop_payments_paypal']['activate']))
		{
			$_POST['wpshop_payments_paypal']['activate'] = 0;
		}
		update_option("wpshop.payments.paypal",$_POST['wpshop_payments_paypal']);
		
		//Наложный платеж
		if (!isset($_POST['wpshop_payments_vizit']['activate']))
		{
			$_POST['wpshop_payments_vizit']['activate'] = 0;
		}
		update_option("wpshop.payments.vizit",$_POST['wpshop_payments_vizit']);

		//Визит в наш офис
		if (!isset($_POST['wpshop_payments_post']['activate']))
		{
			$_POST['wpshop_payments_post']['activate'] = 0;
		}
		update_option("wpshop.payments.post",$_POST['wpshop_payments_post']);
	}	
}
